package com.campus.food.service.impl;

import com.campus.food.mapper.MerchantMapper;
import com.campus.food.mapper.UserMapper;
import com.campus.food.mapper.OrderMapper;
import com.campus.food.mapper.FoodMapper;
import com.campus.food.mapper.OrderDetailMapper;
import com.campus.food.model.entity.Merchant;
import com.campus.food.model.entity.User;
import com.campus.food.model.entity.Order;
import com.campus.food.model.entity.Food;
import com.campus.food.model.entity.OrderDetail;
import com.campus.food.service.MerchantService;
import com.campus.food.exception.BusinessException;
import com.campus.food.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * 商家服务实现类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Service
@Transactional
public class MerchantServiceImpl implements MerchantService {
    
    @Autowired
    private MerchantMapper merchantMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private FoodMapper foodMapper;
    
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    
    @Override
    public Merchant applyMerchant(Merchant merchant) {
        // 验证必填字段
        validateMerchant(merchant);
        
        // 检查用户是否存在
        User user = userMapper.selectById(merchant.getUserId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查用户是否已有商家信息
        if (merchantMapper.existsByUserId(merchant.getUserId())) {
            throw new BusinessException("该用户已申请过商家入驻");
        }
//        user.setRole(2);
//        userMapper.updateById(user);
        // 设置默认值
        merchant.setStatus(0); // 待审核状态
        merchant.setBusinessStatus(0); // 休息中状态
        merchant.setRating(BigDecimal.valueOf(5.0)); // 默认评分
        merchant.setMonthlySales(0); // 默认月销量
        
        // 保存商家信息
        int result = merchantMapper.insert(merchant);
        if (result <= 0) {
            throw new BusinessException("申请失败");
        }
        
        return merchant;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Merchant getMerchantById(Long id) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        return merchant;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Merchant getMerchantByUserId(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return merchantMapper.selectByUserId(userId);
    }
    
    @Override
    public boolean updateMerchant(Merchant merchant) {
        if (merchant.getId() == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 验证必填字段
        validateMerchant(merchant);
        
        // 检查商家是否存在
        Merchant existingMerchant = merchantMapper.selectById(merchant.getId());
        if (existingMerchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        // 验证权限（确保只能修改自己的商家信息）
        if (!existingMerchant.getUserId().equals(merchant.getUserId())) {
            throw new BusinessException("无权限修改此商家信息");
        }
        
        return merchantMapper.updateById(merchant) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateMerchantStatus(Long id, Integer status) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (status == null || (status != 0 && status != 1 && status != 2)) {
            throw new BusinessException("审核状态无效");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        merchantMapper.updateStatus(id, status);
        if (status == 1){
            Long userId = merchant.getUserId();
            User user = new User();
            user.setId(userId);
            user.setRole(2);
        }


        return true;
    }
    
    @Override
    public boolean updateBusinessStatus(Long id, Integer businessStatus) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (businessStatus == null || (businessStatus != 0 && businessStatus != 1)) {
            throw new BusinessException("营业状态无效");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        // 只有审核通过的商家才能修改营业状态
        if (merchant.getStatus() != 1) {
            throw new BusinessException("商家未通过审核，无法修改营业状态");
        }
        
        return merchantMapper.updateBusinessStatus(id, businessStatus) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Merchant> getMerchantList(int page, int size, String shopName, Integer status, Integer businessStatus) {
        int offset = (page - 1) * size;
        return merchantMapper.selectPage(offset, size, shopName, status, businessStatus);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getMerchantCount(String shopName, Integer status, Integer businessStatus) {
        return merchantMapper.selectCount(shopName, status, businessStatus);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Merchant> getMerchantsByStatus(Integer status) {
        return merchantMapper.selectByStatus(status);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Merchant> getMerchantsByBusinessStatus(Integer businessStatus) {
        return merchantMapper.selectByBusinessStatus(businessStatus);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Merchant> getOpenMerchants(int page, int size, String shopName, Double minRating, Double maxRating, 
                                         Integer minSales, Integer maxSales, String orderBy) {
        int offset = (page - 1) * size;
        
        // 处理排序方式
        String sortField = null;
        String sortOrder = null;
        if (StringUtils.hasText(orderBy)) {
            switch (orderBy) {
                case "rating_desc":
                    sortField = "rating";
                    sortOrder = "DESC";
                    break;
                case "rating_asc":
                    sortField = "rating";
                    sortOrder = "ASC";
                    break;
                case "sales_desc":
                    sortField = "monthly_sales";
                    sortOrder = "DESC";
                    break;
                case "sales_asc":
                    sortField = "monthly_sales";
                    sortOrder = "ASC";
                    break;
                default:
                    // 默认按评分降序
                    sortField = "rating";
                    sortOrder = "DESC";
            }
        }
        
        return merchantMapper.selectOpenMerchants(offset, size, shopName, minRating, maxRating, minSales, maxSales, sortField, sortOrder);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getOpenMerchantsCount(String shopName, Double minRating, Double maxRating, Integer minSales, Integer maxSales) {
        return merchantMapper.selectOpenMerchantsCount(shopName, minRating, maxRating, minSales, maxSales);
    }
    
    @Override
    public boolean updateRating(Long id, Double rating) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (rating == null || rating < 0 || rating > 5) {
            throw new BusinessException("评分必须在0-5之间");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        return merchantMapper.updateRating(id, rating) > 0;
    }
    
    @Override
    public boolean updateMonthlySales(Long id, Integer monthlySales) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (monthlySales == null || monthlySales < 0) {
            throw new BusinessException("月销量不能为负数");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        return merchantMapper.updateMonthlySales(id, monthlySales) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean existsByUserId(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        return merchantMapper.existsByUserId(userId);
    }
    
    @Override
    public boolean deleteMerchant(Long id) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        return merchantMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional
    public boolean auditMerchant(Long id, Integer status, String reason) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (status == null || (status != 1 && status != 2)) {
            throw new BusinessException("审核状态必须为1(通过)或2(拒绝)");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        // 如果状态是拒绝，必须提供拒绝理由
        if (status == 2 && !StringUtils.hasText(reason)) {
            throw new BusinessException("拒绝时必须提供审核意见");
        }
        if (status == 1){
            Merchant merchant1 = merchantMapper.selectById(id);
            Long userId = merchant1.getUserId();
            User user = new User();
            user.setRole(2);
            user.setId(userId);
            userMapper.updateById(user);

        }
        
        return merchantMapper.updateStatus(id, status) > 0;
    }
    
    /**
     * 验证商家信息
     */
    private void validateMerchant(Merchant merchant) {
        if (merchant == null) {
            throw new BusinessException("商家信息不能为空");
        }

        Long currentUserId = SecurityUtil.getCurrentUserId();

        merchant.setUserId(currentUserId);
        if (merchant.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (!StringUtils.hasText(merchant.getShopName())) {
            throw new BusinessException("店铺名称不能为空");
        }
        
        if (!StringUtils.hasText(merchant.getShopAddress())) {
            throw new BusinessException("店铺地址不能为空");
        }
        
        if (!StringUtils.hasText(merchant.getContactPhone())) {
            throw new BusinessException("联系电话不能为空");
        }
    }

    @Override
    public Object getStatistics(Long id, String startTime, String endTime) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        // 解析时间范围
        LocalDateTime start = null;
        LocalDateTime end = null;
        
        if (StringUtils.hasText(startTime)) {
            start = LocalDateTime.parse(startTime + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        
        if (StringUtils.hasText(endTime)) {
            end = LocalDateTime.parse(endTime + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        
        // 查询商家在指定时间范围内的订单统计数据
        Map<String, Object> statistics = new HashMap<>();
        
        // 查询订单总数
        Long orderCount = orderMapper.selectCountByMerchantAndTimeRange(id, start, end, null);
        statistics.put("orderCount", orderCount == null ? 0 : orderCount);
        
        // 查询销售总额
        Double totalAmount = orderMapper.selectSalesAmountByMerchantAndTimeRange(id, start, end, null);
        statistics.put("totalAmount", totalAmount == null ? 0.0 : totalAmount);
        
        // 查询已完成订单数
        Long completedCount = orderMapper.selectCountByMerchantAndTimeRange(id, start, end, 4); // 4-已完成
        statistics.put("completedCount", completedCount == null ? 0 : completedCount);
        
        // 查询已取消订单数
        Long cancelledCount = orderMapper.selectCountByMerchantAndTimeRange(id, start, end, 5); // 5-已取消
        statistics.put("cancelledCount", cancelledCount == null ? 0 : cancelledCount);
        
        // 计算平均客单价
        Double averageAmount = 0.0;
        if (orderCount != null && orderCount > 0 && totalAmount != null) {
            averageAmount = totalAmount / orderCount;
        }
        statistics.put("averageAmount", averageAmount);
        
        return statistics;
    }
    
    @Override
    public List<Object> getOrderTrend(Long id, String startTime, String endTime, String timeUnit) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        // 校验时间单位
        if (!timeUnit.equals("day") && !timeUnit.equals("week") && !timeUnit.equals("month")) {
            throw new BusinessException("时间单位必须为day、week或month");
        }
        
        // 解析时间范围
        LocalDateTime start = null;
        LocalDateTime end = null;
        
        if (StringUtils.hasText(startTime)) {
            start = LocalDateTime.parse(startTime + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认开始时间为30天前
            start = LocalDateTime.now().minusDays(30).withHour(0).withMinute(0).withSecond(0);
        }
        
        if (StringUtils.hasText(endTime)) {
            end = LocalDateTime.parse(endTime + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认结束时间为当前时间
            end = LocalDateTime.now();
        }
        
        // 根据时间单位，查询订单趋势数据
        List<Object> trendData = new ArrayList<>();
        
        // 查询指定时间范围内该商家的所有订单
        List<Order> orders = orderMapper.selectOrdersByMerchantAndTimeRange(id, start, end);
        
        if (orders == null || orders.isEmpty()) {
            return trendData;
        }
        
        // 按时间单位分组统计
        Map<String, Map<String, Object>> trendMap = new HashMap<>();
        
        for (Order order : orders) {
            String dateKey;
            LocalDateTime orderTime = order.getCreateTime();
            
            if ("day".equals(timeUnit)) {
                // 按天分组
                dateKey = orderTime.toLocalDate().toString();
            } else if ("week".equals(timeUnit)) {
                // 按周分组，使用年份+周数作为key
                dateKey = orderTime.getYear() + "年第" + (orderTime.getDayOfYear() / 7 + 1) + "周";
            } else {
                // 按月分组
                dateKey = orderTime.getYear() + "-" + String.format("%02d", orderTime.getMonthValue());
            }
            
            // 计入统计结果
            if (!trendMap.containsKey(dateKey)) {
                Map<String, Object> dataItem = new HashMap<>();
                dataItem.put("date", dateKey);
                dataItem.put("orderCount", 0L);
                dataItem.put("amount", 0.0);
                trendMap.put(dateKey, dataItem);
            }
            
            Map<String, Object> dataItem = trendMap.get(dateKey);
            Long orderCount = (Long) dataItem.get("orderCount");
            Double amount = (Double) dataItem.get("amount");
            
            orderCount += 1;
            amount += order.getActualAmount().doubleValue();
            
            dataItem.put("orderCount", orderCount);
            dataItem.put("amount", amount);
        }
        
        // 转换成列表并排序
        List<Map<String, Object>> sortedData = new ArrayList<>(trendMap.values());
        sortedData.sort((a, b) -> ((String) a.get("date")).compareTo((String) b.get("date")));
        
        return new ArrayList<>(sortedData);
    }
    
    @Override
    public List<Object> getFoodSalesProportion(Long id, String startTime, String endTime, Integer limit) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        if (limit == null || limit <= 0) {
            limit = 10; // 默认查询前10个
        }
        
        // 解析时间范围
        LocalDateTime start = null;
        LocalDateTime end = null;
        
        if (StringUtils.hasText(startTime)) {
            start = LocalDateTime.parse(startTime + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认开始时间为30天前
            start = LocalDateTime.now().minusDays(30).withHour(0).withMinute(0).withSecond(0);
        }
        
        if (StringUtils.hasText(endTime)) {
            end = LocalDateTime.parse(endTime + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认结束时间为当前时间
            end = LocalDateTime.now();
        }
        
        // 查询菜品销售占比数据
        List<Object> salesData = new ArrayList<>();
        
        // 查询指定时间范围内的订单
        List<Order> orders = orderMapper.selectOrdersByMerchantAndTimeRange(id, start, end);
        
        if (orders == null || orders.isEmpty()) {
            return salesData;
        }
        
        // 统计每个菜品的销售量
        Map<Long, Map<String, Object>> foodSalesMap = new HashMap<>();
        
        // 遍历所有订单，查询订单详情
        for (Order order : orders) {
            // 只统计已完成的订单
            if (order.getStatus() != 4) {
                continue;
            }
            
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
            
            for (OrderDetail detail : orderDetails) {
                Long foodId = detail.getFoodId();
                
                if (!foodSalesMap.containsKey(foodId)) {
                    // 查询菜品信息
                    Food food = foodMapper.selectById(foodId);
                    if (food == null) {
                        continue;
                    }
                    
                    Map<String, Object> foodData = new HashMap<>();
                    foodData.put("foodId", foodId);
                    foodData.put("foodName", food.getName());
                    foodData.put("price", food.getPrice());
                    foodData.put("salesCount", 0);
                    foodData.put("salesAmount", 0.0);
                    foodSalesMap.put(foodId, foodData);
                }
                
                Map<String, Object> foodData = foodSalesMap.get(foodId);
                Integer salesCount = (Integer) foodData.get("salesCount");
                Double salesAmount = (Double) foodData.get("salesAmount");
                
                salesCount += detail.getQuantity();
                salesAmount += detail.getPrice().doubleValue() * detail.getQuantity();
                
                foodData.put("salesCount", salesCount);
                foodData.put("salesAmount", salesAmount);
            }
        }
        
        // 转换为列表并计算占比
        List<Map<String, Object>> foodSalesList = new ArrayList<>(foodSalesMap.values());
        
        // 按销量排序
        foodSalesList.sort((a, b) -> {
            Integer salesA = (Integer) a.get("salesCount");
            Integer salesB = (Integer) b.get("salesCount");
            return salesB.compareTo(salesA);
        });
        
        // 限制数量并计算占比
        int totalSales = 0;
        
        // 计算总销量
        for (Map<String, Object> foodData : foodSalesList) {
            totalSales += (Integer) foodData.get("salesCount");
        }
        
        // 截取前limit个并计算占比
        for (int i = 0; i < Math.min(limit, foodSalesList.size()); i++) {
            Map<String, Object> foodData = foodSalesList.get(i);
            Integer salesCount = (Integer) foodData.get("salesCount");
            
            double percentage = totalSales > 0 ? (double) salesCount / totalSales * 100 : 0;
            foodData.put("percentage", percentage);
            
            salesData.add(foodData);
        }
        
        return salesData;
    }
    
    @Override
    public Object getOrderStatusDistribution(Long id, String startTime, String endTime) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        // 解析时间范围
        LocalDateTime start = null;
        LocalDateTime end = null;
        
        if (StringUtils.hasText(startTime)) {
            start = LocalDateTime.parse(startTime + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认开始时间为30天前
            start = LocalDateTime.now().minusDays(30).withHour(0).withMinute(0).withSecond(0);
        }
        
        if (StringUtils.hasText(endTime)) {
            end = LocalDateTime.parse(endTime + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认结束时间为当前时间
            end = LocalDateTime.now();
        }
        
        // 查询订单状态分布数据
        Map<Integer, Integer> distribution = new HashMap<>();
        
        // 初始化各状态计数（订单状态：1-待付款，2-待接单，3-配送中，4-已完成，5-已取消）
        distribution.put(1, 0);  // 待付款
        distribution.put(2, 0);  // 待接单
        distribution.put(3, 0);  // 配送中
        distribution.put(4, 0);  // 已完成
        distribution.put(5, 0);  // 已取消
        
        // 查询指定时间范围内的订单
        List<Order> orders = orderMapper.selectOrdersByMerchantAndTimeRange(id, start, end);
        
        if (orders != null && !orders.isEmpty()) {
            // 统计各状态订单数量
            for (Order order : orders) {
                Integer status = order.getStatus();
                if (status >= 1 && status <= 5) {
                    distribution.put(status, distribution.get(status) + 1);
                }
            }
        }
        
        return distribution;
    }
    
    @Override
    public List<Object> getCustomerStatistics(Long id, String startTime, String endTime) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        // 解析时间范围
        LocalDateTime start = null;
        LocalDateTime end = null;
        
        if (StringUtils.hasText(startTime)) {
            start = LocalDateTime.parse(startTime + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认开始时间为7天前
            start = LocalDateTime.now().minusDays(7).withHour(0).withMinute(0).withSecond(0);
        }
        
        if (StringUtils.hasText(endTime)) {
            end = LocalDateTime.parse(endTime + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认结束时间为当前时间
            end = LocalDateTime.now();
        }
        
        // 查询客户统计数据
        List<Object> customerData = new ArrayList<>();
        
        // 查询指定时间范围内的订单
        List<Order> orders = orderMapper.selectOrdersByMerchantAndTimeRange(id, start, end);
        
        if (orders == null || orders.isEmpty()) {
            return customerData;
        }
        
        // 按日期统计下单用户数量
        Map<String, Set<Long>> dateCustomerMap = new HashMap<>();
        
        for (Order order : orders) {
            LocalDate orderDate = order.getCreateTime().toLocalDate();
            String dateKey = orderDate.toString();
            
            if (!dateCustomerMap.containsKey(dateKey)) {
                dateCustomerMap.put(dateKey, new HashSet<>());
            }
            
            dateCustomerMap.get(dateKey).add(order.getUserId());
        }
        
        // 生成有序的日期列表（从开始日期到结束日期）
        LocalDate currentDate = start.toLocalDate();
        LocalDate endDate = end.toLocalDate();
        
        while (!currentDate.isAfter(endDate)) {
            String dateKey = currentDate.toString();
            
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", dateKey);
            
            // 获取当天的独立客户数
            int customerCount = 0;
            if (dateCustomerMap.containsKey(dateKey)) {
                customerCount = dateCustomerMap.get(dateKey).size();
            }
            
            dayData.put("customerCount", customerCount);
            customerData.add(dayData);
            
            currentDate = currentDate.plusDays(1);
        }
        
        return customerData;
    }
    
    @Override
    public List<Object> getHotFoods(Long id, String startTime, String endTime, Integer limit) {
        if (id == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查商家是否存在
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        if (limit == null || limit <= 0) {
            limit = 20; // 默认查询前20个
        }
        
        // 解析时间范围
        LocalDateTime start = null;
        LocalDateTime end = null;
        
        if (StringUtils.hasText(startTime)) {
            start = LocalDateTime.parse(startTime + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认开始时间为30天前
            start = LocalDateTime.now().minusDays(30).withHour(0).withMinute(0).withSecond(0);
        }
        
        if (StringUtils.hasText(endTime)) {
            end = LocalDateTime.parse(endTime + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            // 默认结束时间为当前时间
            end = LocalDateTime.now();
        }
        
        // 查询热销商品数据
        List<Object> hotFoodsList = new ArrayList<>();
        
        // 查询指定时间范围内的订单
        List<Order> orders = orderMapper.selectOrdersByMerchantAndTimeRange(id, start, end);
        
        if (orders == null || orders.isEmpty()) {
            return hotFoodsList;
        }
        
        // 统计每个菜品的销售量和销售额
        Map<Long, Map<String, Object>> foodSalesMap = new HashMap<>();
        
        // 只统计已完成的订单
        for (Order order : orders) {
            if (order.getStatus() != 4) { // 4-已完成
                continue;
            }
            
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(order.getId());
            
            for (OrderDetail detail : orderDetails) {
                Long foodId = detail.getFoodId();
                
                if (!foodSalesMap.containsKey(foodId)) {
                    // 查询菜品信息
                    Food food = foodMapper.selectById(foodId);
                    if (food == null) {
                        continue;
                    }
                    
                    Map<String, Object> foodData = new HashMap<>();
                    foodData.put("foodId", foodId);
                    foodData.put("foodName", food.getName());
                    foodData.put("price", food.getPrice().doubleValue());
                    foodData.put("salesCount", 0);
                    foodData.put("salesAmount", 0.0);
                    foodSalesMap.put(foodId, foodData);
                }
                
                Map<String, Object> foodData = foodSalesMap.get(foodId);
                Integer salesCount = (Integer) foodData.get("salesCount");
                Double salesAmount = (Double) foodData.get("salesAmount");
                
                salesCount += detail.getQuantity();
                salesAmount += detail.getPrice().doubleValue() * detail.getQuantity();
                
                foodData.put("salesCount", salesCount);
                foodData.put("salesAmount", salesAmount);
            }
        }
        
        // 计算总销量
        int totalSales = 0;
        for (Map<String, Object> foodData : foodSalesMap.values()) {
            totalSales += (Integer) foodData.get("salesCount");
        }
        
        // 转换为列表并按销量排序
        List<Map<String, Object>> sortedList = new ArrayList<>(foodSalesMap.values());
        sortedList.sort((a, b) -> {
            Integer salesA = (Integer) a.get("salesCount");
            Integer salesB = (Integer) b.get("salesCount");
            return salesB.compareTo(salesA);
        });
        
        // 截取前limit个并计算占比
        for (int i = 0; i < Math.min(limit, sortedList.size()); i++) {
            Map<String, Object> foodData = sortedList.get(i);
            Integer salesCount = (Integer) foodData.get("salesCount");
            
            // 计算占比
            double percentage = totalSales > 0 ? (double) salesCount / totalSales * 100 : 0;
            foodData.put("percentage", percentage);
            
            hotFoodsList.add(foodData);
        }
        
        return hotFoodsList;
    }
} 